package com.xiaotu.storage;

import java.util.Date;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.xiaotu.common.exception.SpiderException;
import com.xiaotu.common.exception.SpiderExceptionCode;
import com.xiaotu.common.model.SpiderLogModel;
import com.xiaotu.common.util.Constants;
import com.xiaotu.common.util.DateUtils;
import com.xiaotu.common.util.SpringContextHolder;
import com.xiaotu.common.util.UUIDUtils;
import com.xiaotu.spider.monitor.SpiderMonitorThread;
import com.xiaotu.storage.thread.CSVStorageThread;

/**
 * @类名 StorageRunner
 * @日期 2017年2月21日
 * @作者 高海军
 * @功能 数据转储程序入口类
 */
public class StorageRunner
{
	private static final Logger LOGGER = LoggerFactory
			.getLogger(StorageRunner.class);
	
	private static final String DATE_FORMAT = "yyyy-MM-dd";
	
	/**
	 * 转储任务入口
	 * @param args 任务名称、转储文件、代转储数据的日期，格式：“yyyy-MM-dd”
	 */
	public static void main(String[] args)
	{
		
		SpiderLogModel taskLog = new SpiderLogModel();
		taskLog.setSeriesNo(UUIDUtils.getStringUUID());
		try
		{
			SpringContextHolder.setApplicationContext();
			
			taskLog.setStartTime(System.currentTimeMillis());
			taskLog.setSpiderStatus(SpiderMonitorThread.STATUS_RUNNING);
			taskLog.setServType(Constants.LogConstants.SERV_STORAGE);
			
			if (args == null || args.length < 2)
				throw new SpiderException(
						SpiderExceptionCode.StorageProcessorParameterErrorException,
						"args is error");
			
			final ACSVStorageProcessor processor = SpringContextHolder.getBean(
					args[0] + "StorageProcessor", ACSVStorageProcessor.class);
			taskLog.setJobType(processor.getTaskType());
			processor.setTaskLog(taskLog);
			
			Date date = args.length > 2
					? DateUtils.fomartStringToDate(args[2], DATE_FORMAT)
					: DateUtils.getBeforeDay(new Date());
			new CSVStorageThread(args[1], processor, date).run();
			taskLog.setSpiderStatus(SpiderMonitorThread.STATUS_STOPPED);
			
			LOGGER.debug("[{}] Storage Task Finished! ",
					processor.getTaskType());
		}
		catch (Exception e)
		{
			taskLog.setSpiderStatus(SpiderMonitorThread.STATUS_STOPPED);
			taskLog.setException(e.getClass().getSimpleName());
			taskLog.setMessage(e.getMessage());
			LOGGER.error(StringUtils.EMPTY, e);
		}
		finally
		{
			try
			{
				SpringContextHolder
						.getBean("spiderMonitorThread",
								SpiderMonitorThread.class)
						.refreshTaskLog(taskLog);
			}
			catch (Exception e)
			{
				LOGGER.error(StringUtils.EMPTY, e);
			}
		}
	}
}
